package common

import (
	"fmt"
	"github.com/beego/beego/v2/core/logs"
	"io/ioutil"
	"net"
	"os"
	"strings"
)

var gNavigateDir string

func Init(mediaDir string) {
	gNavigateDir = mediaDir
}

func FileIsExist(filepath string) bool {

	f, err := os.Stat(filepath)
	if err != nil && os.IsNotExist(err) {
		return false
	}

	if f.IsDir() {
		return false
	}

	return true

}

func MediaFullPath(appId, media string) string {

	if len(media) == 0 {
		return ""
	}

	if strings.HasPrefix(media, "/") {
		return media
	}
	return gNavigateDir + appId + "/" + media
}

func CreateSipAcountFile(acct, pwd, path string) error {

	sipContet :=
		"<include>\n" +
			"  <user id=\"" + acct + "\">\n" +
			"    <params>\n" +
			"      <param name=\"password\" value=\"" + pwd + "\"/>\n" +
			"      <param name=\"vm-password\" value=\"" + acct + "\"/>\n" +
			"    </params>\n" +
			"    <variables>\n" +
			"      <variable name=\"toll_allow\" value=\"domestic,international,local\"/>\n" +
			"      <variable name=\"accountcode\" value=\"" + acct + "\"/>\n" +
			"      <variable name=\"user_context\" value=\"default\"/>\n" +
			"      <variable name=\"sip-force-contact\" value=\"NDLB-connectile-dysfunction-2.0\"/>\n" +
			"      <variable name=\"effective_caller_id_name\" value=\"Extension " + acct + "\"/>\n" +
			"      <variable name=\"effective_caller_id_number\" value=\"" + acct + "\"/>\n" +
			"      <variable name=\"callgroup\" value=\"techsupport\"/>\n" +
			"    </variables>\n" +
			"  </user>\n" +
			"</include>\n"

	var d = []byte(sipContet)

	fileName := fmt.Sprintf("%s/%s.xml", path, acct)
	err := ioutil.WriteFile(fileName, d, 0666)
	logs.Debug("创建坐席文件:%v 结果:%v", fileName, err)
	return err
}

func GetLocalAddr() string {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		fmt.Println(err)
		return ""
	}
	for _, address := range addrs {
		// 检查ip地址判断是否回环地址
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				return (ipnet.IP.String())
			}
		}
	}
	return ""
}

func WeekParse(weekStr string) (result [7]bool) {

	if len(weekStr) == 0 {
		for i := 0; i < 7; i++ {
			result[i] = true
		}
		return
	}

	weeks := strings.Split(weekStr, ",")
	logs.Debug("分解星期：%v:%v", weekStr, weeks)
	for _, w := range weeks {

		switch w {

		case "SUN":
			result[0] = true
		case "MON":
			result[1] = true
		case "TUES":
			result[2] = true
		case "WED":
			result[3] = true
		case "THUR":
			result[4] = true
		case "FRI":
			result[5] = true
		case "SAT":
			result[6] = true
		}
	}

	return
}

func DetectNumberIsSipAcct(number string) bool {

	if len(number) == 14 || len(number) == 6 {
		return true
	} else {
		return false
	}
}
